package struct.arrays;

/**
 * @author: kanggw
 * @date: 2022/3/1
 * @DESCRIPTION:搜索二维矩阵
 * 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性：
 *
 * 每行的元素从左到右升序排列。
 * 每列的元素从上到下升序排列
 * 链接：https://leetcode-cn.com/leetbook/read/top-interview-questions/xmlwi1/
 *
 * 输入：matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
 * 输出：true
 *
 * 输入：matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
 * 输出：false
 *
 */
public class MatrixSearch {


    public static void main(String[] args) {

        int[][] matrix = {{1,4,7,11,15}, {2,5,8,12,19},{3,6,9,16,22},{10,13,14,17,24},{18,21,23,26,30}};
        int target = 18;

        final boolean b = forceSearch(matrix, target);
        System.out.println("out:" + b);

        final boolean b1 = fromBottomLeft(matrix, target);

        System.out.println("out:" + b1);
    }

    /**
     * 暴力破解
     */
    public static boolean forceSearch(int[][] matrix,int target) {

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 从左下角或者右上角开始找
     * @param matrix
     * @param target
     * @return
     */
    public static boolean fromBottomLeft(int[][] matrix, int target) {

        int row = matrix.length - 1;
        int col = 0;
        while (row >= 0 && col < matrix[row].length) {
            if (target == matrix[row][col]) {
                return true;
            } else if (target > matrix[row][col]) {
                col++;
            } else {
                row--;
            }
        }

        return false;
    }


}
